/*
 * Copyright (C) 2007-2008  Hylke van der Schaaf
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, in version 3 of the License.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package hextd.message;

import hextd.message.MessageFactory.NetworkMessage;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MessageMap implements Message {

	public NetworkMessage type = NetworkMessage.Map;
	public static String RegExp = "MAP ([-0-9]+) ([^\\n]+)";
	public static Pattern MessagePattern = Pattern.compile(MessageMap.RegExp);
	//
	private String message;
	private String map;
	private int mapId;

	public static String formatMessage(int mapId, String mapCode) {
		String message = "";
		try {
			message = "MAP " + mapId + " " + URLEncoder.encode(mapCode, "UTF-8");
		} catch (UnsupportedEncodingException ex) {
			Logger.getLogger(MessageMap.class.getName()).log(Level.SEVERE, null, ex);
		}
		return message;
	}

	public MessageMap() {
	}

	private MessageMap(String message) {
		this.message = message;
		Matcher matcher = MessageMap.MessagePattern.matcher(message);
		if (matcher.matches()) {
			try {
				this.mapId = Integer.parseInt(matcher.group(1));
				this.map = URLDecoder.decode(matcher.group(2), "UTF-8");
			} catch (NumberFormatException e) {
				System.err.println("MessageSay: invalid id in: " + matcher.group(1));
			} catch (UnsupportedEncodingException ex) {
				Logger.getLogger(MessageMap.class.getName()).log(Level.SEVERE, null, ex);
			}
		}
	}

	public String getMap() {
		return map;
	}

	public int getMapId() {
		return mapId;
	}

	@Override
	public String getMessage() {
		return this.message;
	}

	@Override
	public Message initFromString(String message) {
		return new MessageMap(message);
	}

	@Override
	public int getSenderId() {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	@Override
	public void setSenderId(int id) {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	@Override
	public Pattern getPattern() {
		return MessageMap.MessagePattern;
	}

	@Override
	public NetworkMessage getType() {
		return this.type;
	}
}
